package com.stox.services.screener.screen.gainer;

import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stox.services.data.provider.manager.BarManager;
import com.stox.services.data.provider.manager.ScripManager;
import com.stox.services.screener.model.AbstractScreen;
import com.stox.services.screener.model.Scan;
import com.stox.shared.beans.BeanDescriptor;
import com.stox.shared.model.Bar;
import com.stox.shared.model.ScreenerConfiguration;
import com.stox.shared.model.Scrip;
import com.stox.shared.model.enumeration.BarValue;
import com.stox.shared.util.BarUtil;

@Component
public class GainerScreen extends AbstractScreen<GainerScreenConfiguration, GainerScreenMatch> implements InitializingBean{

	@Autowired
	private ScripManager scripManager;
	
	@Autowired
	private BarManager barManager;
	
	public GainerScreen() {
		super("GainerScreen",  new GainerScreenConfiguration(), 
				new BeanDescriptor(new GainerScreenMatch(null, 0, 0)));
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		setBarManager(barManager);
		setScripManager(scripManager);
	}
	
	@Override
	public void screen(String scanId,
			ScreenerConfiguration screenerConfiguration,
			GainerScreenConfiguration screenConfiguration) {
		super.screen(screenConfiguration.getGainSpan(), scanId, screenerConfiguration, screenConfiguration);
	}
	
	@Override
	public void screen(Scrip scrip, List<Bar> bars, 
			Scan<GainerScreenMatch> scan,
			GainerScreenConfiguration screenConfiguration) {
		double high = 0;
		double low = 0;
		if(screenConfiguration.isMatchExactSpan()){
			high = screenConfiguration.isUseHighLowValues() ? bars.get(0).getHigh() : bars.get(0).getClose();
			low = screenConfiguration.isUseHighLowValues() ? bars.get(bars.size() - 1).getLow() : bars.get(bars.size() - 1).getClose();
		}else{
			Bar highest = BarUtil.highest(bars, screenConfiguration.isUseHighLowValues() ? BarValue.HIGH : BarValue.CLOSE);
			Bar lowest = BarUtil.lowest(bars, screenConfiguration.isUseHighLowValues() ? BarValue.LOW : BarValue.CLOSE);
			if(highest.getDate().after(lowest.getDate())){
				high = screenConfiguration.isUseHighLowValues() ? highest.getHigh() : highest.getClose();
				low = screenConfiguration.isUseHighLowValues() ? lowest.getLow() : lowest.getClose();
			}
		}
		
		if((100*(high-low)/low) >= screenConfiguration.getMinimumGainPercentage()){
			GainerScreenMatch match = new GainerScreenMatch(bars.get(0).getScripId(), low, high);
			scan.addMatch(match);
		}
		
	}
	
}
